package com.kkw.netty.duoxianchengselector;

import com.kkw.utils.ByteBufferUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

/** 多线程版本的selector
 * @author Kevin
 * @date 2021-09-23
 **/
public class MultiThreadServer {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector boss = Selector.open();
        SelectionKey bossKey = ssc.register(boss, 0, null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));
        //创建固定数量的worker 并初始化
        Worker[] workers = new Worker[4];
        // 用于负载均衡的原子整数
        AtomicInteger robin = new AtomicInteger(0);
        for(int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("worker-"+i);
        }
        while (true){
            //channel已经不阻塞了 因为前面已经设置了fasle
            boss.select();
            Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
            while (iter.hasNext()){
                SelectionKey key = iter.next();
                if (key.isAcceptable()){
                    SocketChannel sc = ssc.accept();
                    System.out.println("connected...{}"+sc.getRemoteAddress());
                    sc.configureBlocking(false);
//                    new Worker("selector-0");  不应该放在这里 因为这样会导致一个channel一个worker了 我们的worker数量是固定的
                    //2、关联selector
                    System.out.println("befterRegister...{}"+sc.getRemoteAddress());
                    //round robin
                    workers[robin.getAndIncrement()% workers.length].register(sc);
//                    sc.register(worker.selector,SelectionKey.OP_READ,null);
                    System.out.println("afterRegister...{}"+sc.getRemoteAddress());
                }
            }
        }
    }
    static class  Worker implements Runnable{
        private Thread thread;
        private volatile Selector selector;
        private String name;
        //两个线程之间传递数据可以用queue
        private ConcurrentLinkedQueue<Runnable> queue;

        //还未初始化变量
        private volatile boolean start=false;

        public Worker(String name) {
            this.name = name;
        }

        /**
         * 初始化线程 保证只是执行一遍
         */
        public void register(SocketChannel sc) throws IOException {
            if (!start){
                thread=new Thread(this,name);
                selector =Selector.open();
                queue = new ConcurrentLinkedQueue<>();
                thread.start();
                start=true;
            }
            //还是boss线程调用
            //向队列添加了任务，但这个任务没有立刻执行
            queue.add(()->{
                try {
                    sc.register(selector,SelectionKey.OP_READ,null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            // 唤醒被阻塞的Selector
            // select类似LockSupport中的park，wakeup的原理类似LockSupport中的unpark
            //唤醒一下selector
            selector.wakeup();
        }

        @Override
        public void run() {
            while (true){
                try {
                    selector.select();
                    //通过同步队列获得任务并运行
                    Runnable task = queue.poll();
                    if (task != null) {
                        // 获得任务，执行注册操作
                        task.run();
                    }
                    Iterator<SelectionKey> iter= selector.selectedKeys().iterator();
                    while (iter.hasNext()){
                        SelectionKey key = iter.next();
                        if (key.isReadable()) {
                            iter.remove();
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            System.out.println("worker...read:{"+channel.getRemoteAddress()+"}");
                            channel.read(buffer);
                            buffer.flip();
                            ByteBufferUtil.debugAll(buffer);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
